/*
 * @Descripttion: 对象池工厂
 * @Author: jindekun
 * @Date: 2022-01-28 11:17:45
 */

import * as cc from "cc";

export class PoolFactory {
    /**对象池容器 */
    private _mapPool: { [key: string]: cc.NodePool } = {};
    /**对象池初始节点或预制体 */
    private _mapOriginal: { [key: string]: cc.Node | cc.Prefab} = {};
    /**
     * @desc 创建对象池
     */
    createPool(key: string, original: cc.Node | cc.Prefab, count: number = 1) {
        if(this.hasPool(key)){
            return;
        }
        const pool = new cc.NodePool(key);

        for (let i = 0; i < count; i++) {
            const poolNode = cc.instantiate(original) as cc.Node;
            pool.put(poolNode);
        }

        this._mapOriginal[key] = original;
        this._mapPool[key] = pool;
    }

    /**
     * @desc 取出对象池缓存的节点
     */
    get(key: string): cc.Node {
        if(!this.hasPool(key)){
            return null;
        }
        if (this._mapPool[key].size() > 0) {
            return this._mapPool[key].get();                        
        }
        return cc.instantiate(this._mapOriginal[key]) as cc.Node;
    }

    /**
     * @desc 将节点放回对象池内
     * @param key 
     */
    put(key: string, node: cc.Node) {
        if(!this.hasPool(key)){
            return;
        }
        this._mapPool[key].put(node);
    }

    /**
     * @desc 根据名字清空对象池
     * @param key 
     */
    clearPool(key: string) {
        if(!this.hasPool(key)){
            return;
        }
        this._mapPool[key].clear();
        delete this._mapPool[key];
    }

    /**清除对象池 */
    clearAll() {
        for (const key in this._mapPool) {
            if (Object.prototype.hasOwnProperty.call(this._mapPool, key)) {
                const pool = this._mapPool[key];
                pool.clear();
            }
        }
        this._mapPool = {};
    }

    /**对象池是否存在 */
    hasPool(key:string){
        return !!this._mapPool[key];
    }

}